package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Program: health_parent
 * @Description:
 * @Author: choulan
 * @Date:2020-11-11 14:38
 **/
@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;
    //新增套餐
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        //新增关联关系
        Integer setmealId = setmeal.getId();
        this.setCheckGroupAndSetMeal(setmealId,checkgroupIds);
        //将图片保存到redis
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());

        //生成静态模板页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }
    //生成套餐列表静态页面
    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        Map map=new HashMap();
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }
    //通用的方法，用于生成静态页面
    private void generteHtml(String templateName, String htmlPageName, Map map) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //生成套餐详情静态页面（可能有多个）
    private void generateMobileSetmealListHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map=new HashMap();
            map.put("setmeal",setMealDao.findSetMealById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage,pageSize);
        String queryString = queryPageBean.getQueryString();
        //返回一个page对象
        Page<Setmeal> page=setMealDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Setmeal> rows = page.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public void delete(Integer id) {
        //首先删除表关联
        setMealDao.deleteAssociation(id);
        //再删除套餐
        setMealDao.delete(id);

        //生成静态模板页面
        generateMobileStaticHtml();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }


    @Override
    public List<Integer> findCheckGroupIdsBySetMealId(Integer id) {
        return setMealDao.findCheckGroupIdsBySetMealId(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.edit(setmeal);
        //清除原有的多对多关联关系
        setMealDao.deleteAssociation(setmeal.getId());
        //重新设置checkgroup与checkitem的多对多的关联关系
        Integer setmealId = setmeal.getId();
        this.setCheckGroupAndSetMeal(setmealId,checkgroupIds);

        //生成静态模板页面
        generateMobileStaticHtml();
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    @Override
    public Setmeal findSetMealById(Integer id) {
        return setMealDao.findSetMealById(id);
    }

    @Override
    public List<Map<String, Object>> findSetMealCount() {
        return setMealDao.findSetMealCount();
    }


    //封装关联方法
    public void setCheckGroupAndSetMeal(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds!=null&&checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setMealDao.setCheckGroupAndSetMeal(map);
            }
        }
    }
}
